package com.stu.config.shiro;

import com.stu.pojo.User;
import com.stu.service.UserService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;


public class MyRealm extends AuthorizingRealm {
    //假数据——模拟数据库
    @Autowired
    private UserService userService;

    //授权
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        Subject subject = SecurityUtils.getSubject();
        User user = (User)subject.getPrincipal();
        String perm = user.getPermission();//获取权限

        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();
        info.addStringPermission(perm);//授予权限
        return info;
    }
    //认证
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        String uname = token.getPrincipal().toString();
        String pwd = token.getCredentials().toString();
        //根据username查询用户
        User user = userService.getUserByName(uname);
        if(user==null) return null;//抛出UnknownAccountException，防止NullPointerException
        //可以对密码进行加密

        //认证密码——shiro自己做
        return new SimpleAuthenticationInfo(
                user,//①参数principal：设置用户，如果为空则抛出空指针异常
                user.getPassword(),//②参数credentials：设置密码，如果为空则抛出空指针异常
                this.getName()//③参数realmName：自定义Realm的全路径名
        );
    }
}
//①要保证授权与认证获取的是同一个用户，就要在doGetAuthenticationInfo方法中的返回对象中设置principal参数，用以传递用户名，这样该参数在全局都可以通过SecurityUtils.getSubject().getPrincipal()获得。在授权方法中获得用户名之后，可以根据它查询角色或权限，并进行授权操作。

//doGetAuthenticationInfo()方法：如果返回空则直接抛出UnknownAccountException，该异常可以被调用subject.login(token)的方法捕获
//如果返回SimpleAuthenticationInfo对象，参数principal用于验证用户,可以用subject获取，如果参数principal为null则抛出NullPointerException